<?php
/**
 * @file collection.php
 * @author LJ (liangjian@haibao.com)
 * @date 2015年11月25日 上午11:38:21
 * @brief 收藏图片
 */
namespace haibao\app\data;

class Collection extends \haibao\app\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\app\model\data\Collection');
    }
    
    public function getCollectionById($id){
        $this->getOneById($id);
    }
    
    public function addCollect($model){
        $this->beginTranscation();
        try {
            $this->add($model);
            $this->resetImageCount($model->UserId, $model->AlbumId);
            $cache = new \haibao\app\cache\Album();
            $cache->deleteAlbumTop3($model->UserId);
            $cache->deleteAlbumList($model->UserId);
        }catch (\Exception $e){
            $this->rollback();
            throw $e;
        }
        $this->endTranscation();
    }
    
    public function getCollectionByImageIdArr($userId, $imageIdArr){
        $imageIdStr = implode(',', $imageIdArr);
        $str = preg_replace('/(\d+)/', '%s', $imageIdStr);
        
        array_unshift($imageIdArr, $userId);
        array_push($imageIdArr, $imageIdStr);
        $result = $this->query("select * from Collection where UserId=%s and ImageId in ($str) order by find_in_set(ImageId, %s)", $imageIdArr);
        $retArr = array();
        while ($row = $result->fetch_assoc()){
            array_push($retArr, $row);
        }
        return $retArr;
    }
    
    /**
     * 取消收藏
     */
    public function deleteCollect($userId, $imageId){
        $colect = $this->query('select albumId from Collection where UserId=%s and ImageId=%s limit 1', array(
            $userId, $imageId
        ))->fetch_assoc();
        $this->query('delete from Collection where UserId=%s and ImageId=%s limit 1', array(
            $userId, $imageId
        ));
            
        $cache = new \haibao\app\cache\Album();
        $cache->deleteAlbumTop3($userId);
        $cache->deleteAlbumList($userId);
        
        if($colect['albumId']){
            $this->resetImageCount($userId, $colect['albumId']);
        }
    }
    
    /**
     * 重置相册中收藏图片数量
     */
    public function resetImageCount($userId, $albumId){
        $this->query('update Album set ImageCount=(select count(*) from Collection where UserId=%s and AlbumId=%s) where UserId=%s and Id=%s limit 1', array(
            $userId, $albumId, $userId, $albumId
        ));
    }
    
    public function isCollect($userId, $dividing){
        $result = $this->query('select count(*) as count from Collection where UserId=%s and CreateTime<%s', array(
            $userId, $dividing
        ))->fetch_assoc();
        return intval($result['count']) > 0 ? true : false;
    }
}